from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from database import get_db
from models.project import TestProject
from models.message import Message

from schemas.project import ProjectBase, ProjectOut, ProjectOutWrapper
from schemas.token import Token
from utils.token_utils import get_current_user

router = APIRouter(
    prefix="/api/projects/v1",  # 所有路由的前缀
    tags=["项目管理模块"],  # 文档中的标签
    responses={404: {"description": "Not found"}}  # 统一响应
)


@router.get("/project", summary="获取项目信息", response_model=ProjectOutWrapper)
def get_project(db: Session = Depends(get_db), _=Depends(get_current_user)):
    projects = db.query(TestProject).all()
    return ProjectOutWrapper(
        code=200,
        message="查询项目信息成功",
        data=[ProjectOut.model_validate(project) for project in projects]
    )


@router.post("/project", summary="创建项目", response_model=dict)
def create_project(
        request: ProjectBase,
        db: Session = Depends(get_db),
        current_user: Token = Depends(get_current_user)
):
    # 查重
    if db.query(TestProject).filter(TestProject.name == request.name).first():
        return {"code": 400, "message": "项目名称已存在", "data": {}}

    # 新建项目
    new_project = TestProject(
        name=request.name,
        description=request.description,
        owner=current_user.username
    )
    db.add(new_project)

    # 新建消息记录
    new_message = Message(
        title="创建测试项目成功",
        content="恭喜你刚刚创建了一个自动化项目，您可以添加用例",
        type="info"
    )
    db.add(new_message)

    # 一次性提交
    db.commit()
    db.refresh(new_project)

    return {"code": 200, "message": "创建项目成功", "data": {}}
